package com.example.camerademo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SurfaceCamera extends Activity implements OnClickListener {
	SurfaceView surfaceView;
	Button button;
	Camera camera = null;
	File currentFile = null;
	SurfaceHolder.Callback surfaceHolder=new Callback() {
		
		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			stopPreview();
		}
		
		private void stopPreview() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			stopPreview();
		}
		
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// TODO Auto-generated method stub
			
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_surface_camera);
		initView();
	}
	private void initView() {
		// TODO Auto-generated method stub
		surfaceView = (SurfaceView) findViewById(R.id.sur_preview);
		button = (Button) findViewById(R.id.btn_photo);
		button.setOnClickListener(this);
		surfaceView.getHolder().addCallback(surfaceHolder);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		camera.takePicture(null, null, new PictureCallback() {
			
			@Override
			public void onPictureTaken(byte[] data, Camera camera) {
				// TODO Auto-generated method stub
				try {
					if(saveFile(data)!=null){
						Toast.makeText(getApplicationContext(), "success", 199).show();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			private Object saveFile(byte[] data) throws IOException {
				// TODO Auto-generated method stub
				File dir=new File(Environment.getExternalStorageDirectory(), "picture");
				if(!dir.exists()){
					dir.mkdir();
				}
				currentFile=new File(dir, System.currentTimeMillis()+"jpg");
				if(!currentFile.exists()){
					currentFile.createNewFile();
					FileOutputStream fos=new FileOutputStream(currentFile);
					fos.write(data);
					fos.flush();
					fos.close();
				}
				return currentFile;
			}
		});
	}

}
